{% extends "base.html" %}

{% block title %}人脸识别解锁{% endblock %}

{% block content %}
<div class="row justify-content-center">
    <div class="col-md-8">
        <h2 class="text-center mt-3">人脸识别解锁</h2>
        
        <div class="card mt-4">
            <div class="card-body">
                <h5 class="card-title">操作说明</h5>
                <ul class="list-group list-group-flush">
                    <li class="list-group-item">1. 点击"开始摄像头"按钮启动摄像头</li>
                    <li class="list-group-item">2. 将面部对准摄像头进行身份验证</li>
                    <li class="list-group-item">3. 系统将自动识别并与已录入的人脸数据进行比对</li>
                    <li class="list-group-item">4. 按"停止摄像头"按钮结束识别</li>
                </ul>
            </div>
        </div>
        
        <div class="video-container mt-4">
            <video id="video" class="video-feed" autoplay playsinline></video>
        </div>
        
        <div class="controls">
            <button id="startCamera" class="btn btn-primary">开始摄像头</button>
            <button id="stopCamera" class="btn btn-secondary" disabled>停止摄像头</button>
        </div>
        
        <div id="status" class="status text-center"></div>
        <div id="result" class="text-center mt-2"></div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    let video = document.getElementById('video');
    let startCameraBtn = document.getElementById('startCamera');
    let stopCameraBtn = document.getElementById('stopCamera');
    let statusDiv = document.getElementById('status');
    let resultDiv = document.getElementById('result');
    let stream = null;
    let recognitionInterval = null;
    
    // 启动摄像头
    startCameraBtn.addEventListener('click', async () => {
        try {
            stream = await navigator.mediaDevices.getUserMedia({ video: true });
            video.srcObject = stream;
            startCameraBtn.disabled = true;
            stopCameraBtn.disabled = false;
            statusDiv.innerHTML = '<span class="text-success">摄像头已启动，正在进行人脸识别...</span>';
            
            // 每秒进行一次人脸识别
            recognitionInterval = setInterval(recognizeFace, 1000);
        } catch (err) {
            statusDiv.innerHTML = '<span class="text-danger">无法访问摄像头: ' + err.message + '</span>';
        }
    });
    
    // 停止摄像头
    stopCameraBtn.addEventListener('click', () => {
        if (stream) {
            const tracks = stream.getTracks();
            tracks.forEach(track => track.stop());
            video.srcObject = null;
            stream = null;
        }
        
        if (recognitionInterval) {
            clearInterval(recognitionInterval);
            recognitionInterval = null;
        }
        
        startCameraBtn.disabled = false;
        stopCameraBtn.disabled = true;
        statusDiv.innerHTML = '<span class="text-info">摄像头已停止</span>';
    });
    
    // 人脸识别函数
    function recognizeFace() {
        const canvas = document.createElement('canvas');
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        const ctx = canvas.getContext('2d');
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
        
        // 转换为base64格式
        const imageData = canvas.toDataURL('image/jpeg');
        
        // 发送到服务器进行识别
        fetch('/api/unlock', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ image: imageData })
        })
        .then(response => response.json())
        .then(data => {
            if (!data.success) {
                resultDiv.innerHTML = `<div class="alert alert-danger">${data.message}</div>`;
                return;
            }
            
            if (data.face_detected === false) {
                resultDiv.innerHTML = '<div class="alert alert-warning">未检测到人脸</div>';
                return;
            }
            
            if (data.match) {
                resultDiv.innerHTML = `
                    <div class="alert alert-success">
                        <h4>解锁成功！</h4>
                        <p>距离: ${data.distance.toFixed(3)} (阈值: ${data.threshold})</p>
                    </div>
                `;
            } else {
                resultDiv.innerHTML = `
                    <div class="alert alert-danger">
                        <h4>访问被拒绝</h4>
                        <p>距离: ${data.distance.toFixed(3)} (阈值: ${data.threshold})</p>
                    </div>
                `;
            }
        })
        .catch(error => {
            resultDiv.innerHTML = `<div class="alert alert-danger">识别失败: ${error.message}</div>`;
        });
    }
</script>
{% endblock %}